﻿using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using EnvDTE;
using JetBrains;
using JetBrains.Annotations;
using JetBrains.Application;
using JetBrains.ProjectModel;
using JetBrains.VsIntegration.ProjectModel.PropertiesExtender;

namespace GammaJul.ReSharper.GammaXaml.Caliburn {

	[ClassInterface(ClassInterfaceType.None)]
	[ComVisible(true)]
	public class GammaXamlPropertiesExtender : ProjectPropertiesExtenderBase {

		[UsedImplicitly]
		[Description("Specifies whether XAML views in this project are using Caliburn.Micro default conventions. The Auto value checks for the presence of a Caliburn.Micro reference.")]
		[DefaultValue(CaliburnSupportTypeConverter.Auto)]
		[DisplayName("Caliburn.Micro Support")]
		[Category("ReSharper")]
		[TypeConverter(typeof(CaliburnSupportTypeConverter))]
		public string CaliburnSupport {
			get {
				try {
					string result = CaliburnSupportTypeConverter.Auto;
					VSExtenderUtils.ExecuteReadLock(Shell.Instance.GetComponent<IShellLocks>(), "GammaXamlPropertiesExtender.CaliburnSupport.get", () => {
						IProject project = Project;
						if (project != null && project.IsValid())
							result = project.GetConfiguredCaliburnSupport().ToString();
					});
					return result;
				}
				catch (InvalidOperationException) {
					// we can get here if the plugin is disabled in R# but not uninstalled from VS
					return Caliburn.CaliburnSupport.No.ToString();
				}
			}
			set {
				try {
					VSExtenderUtils.ExecuteReadLock(Shell.Instance.GetComponent<IShellLocks>(), "GammaXamlPropertiesExtender.CaliburnSupport.set", () => {
						IProject project = Project;
						if (project != null && project.IsValid())
							project.SetConfiguredCaliburnSupport(value.ToEnumSafe(Caliburn.CaliburnSupport.Auto));
					});
				}
				catch (InvalidOperationException) {
					// we can get here if the plugin is disabled in R# but not uninstalled from VS
				}
			}
		}

		public GammaXamlPropertiesExtender(IProject project, IExtenderSite site, int cookie)
			: base(project, site, cookie) {
		}

	}

}